import React, {useRef, useEffect} from 'react'

const InfiniteScroll = props => {
  const {data, loadData, renderItem, className = '', itemClassName = '', more = false, renderLoading, renderFooter} = props
  const obRef = useRef({})
  const footerRef = useRef()

  useEffect(() => {
    try {
      if (!(obRef.current instanceof IntersectionObserver)) {
        obRef.current = new IntersectionObserver(entries => {
          if (entries[0].intersectionRatio <= 0) return;
          loadData()
        })
        obRef.current.observe(footerRef.current)
      }
    } catch (e) {
      console.error(e)
    }
    return () => {
      try {
        if (obRef.current instanceof IntersectionObserver) {
          obRef.current.unobserve(footerRef.current)
          obRef.current = null
          footerRef.current = null
        }
      } catch (e) {
        console.error(e)
      }
    }
  }, [])

  return (
    <ul className={`infinite-scroll ${className}`}>
      {data.map((d, index) => (
        <li key={index} className={itemClassName}>{renderItem(d, index)}</li>
      ))}
      <li ref={footerRef} style={more ? {textAlign: 'center', padding: '2vw'} : {padding: 0}}>
        {more ? (renderLoading && renderLoading() || 'loading···') : ''}
      </li>
      {renderFooter && renderFooter()}
    </ul>
  )
}

export default InfiniteScroll
